<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="channelQueryForm" :inline="true">
        <el-form-item :label="$t('channel.comChannel')" prop="channelId">
          <el-select
              v-model="channelQueryForm.channelId"
              :placeholder="
              $t('common.placeholderSelect') + $t('channel.comChannel')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in channelList"
                :key="index"
                :label="locale ? item.channelCnName : item.channelEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}
          </el-button>
          <el-button @click="addchannel" type="primary" icon="Plus">{{
              $t("common.add")
            }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
        :dialog-title="dialogTitle"
        v-model="dialogVisible"
        :dialog-width="dialogWidth"
        :form-data="channelForm"
        :form-rules="channelRules"
        :submit-loading="submitLoading"
        @close="close"
        @cancel="cancel"
        @submit="handleFormSubmit"
        @before-close="handleDialogBeforeClose"
        ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>

        <el-form-item :label="$t('channel.channelCnName')" prop="channelCnName">
          <el-input
              v-model="channelForm.channelCnName"
              :placeholder="
              $t('common.placeholderInput') + $t('channel.channelCnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('channel.channelEnName')" prop="channelEnName">
          <el-input
              v-model="channelForm.channelEnName"
              :placeholder="
              $t('common.placeholderInput') + $t('channel.channelEnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item
            :label="$t('channel.timePeriod')"
            prop="timePeriod"
        >
          <el-input-number
              v-model="channelForm.timePeriod"
              :placeholder="
              $t('common.placeholderInput') + $t('channel.timePeriod')
            "
              :min="1"
              :max="99999"
          />
        </el-form-item>
        <el-form-item :label="$t('channel.protType')" prop="protType">
          <el-select
              v-model="channelForm.protType"
              :placeholder="
              $t('common.placeholderSelect') + $t('channel.protType')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in channelTypeEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('channel.channelEnable')" prop="isEnable">
          <el-select
              v-model="channelForm.isEnable"
              :placeholder="
              $t('common.placeholderSelect') + $t('channel.channelEnable')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in isEnableEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('channel.isInner')" prop="isInner">
          <el-select
              v-model="channelForm.isInner"
              :placeholder="
              $t('common.placeholderSelect') + $t('channel.isInner')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in isInnerEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('channel.comment')" prop="comment">
          <el-input
              v-model="channelForm.comment"
              :placeholder="
              $t('common.placeholderInput') + $t('channel.comment')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
          ><!-- 数据表格 -->
            <el-table
                max-height="600"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
              <el-table-column
                  :label="$t('common.sn')"
                  type="index"
                  width="150"
              />
              <el-table-column
                  :label="$t('channel.channelCnName')"
                  align="center"
                  prop="channelCnName"
              >
              </el-table-column>
              <el-table-column
                  :label="$t('channel.channelEnName')"
                  align="center"
                  prop="channelEnName"
              />
              <el-table-column
                  :label="$t('channel.timePeriod')"
                  align="center"
                  prop="timePeriod"
              />

              <el-table-column
                  :label="$t('channel.protType')"
                  align="center"
                  prop="protType"
              >
                <template #default="scope">
                  {{ getchannelTypeNameById(scope.row.protType) }}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('channel.isInner')"
                  align="center"
                  prop="isInner"
              >
                <template #default="scope">
                  {{ getisInnerTypeNameById(scope.row.isInner) }}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('channel.timePeriod')"
                  align="center"
                  prop="timePeriod"
              >
                <template #default="scope">
                  <el-tag @click="goTopic(scope.row)">
                    {{$t('channel.channles')}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('channel.comment')"
                  align="center"
                  prop="comment"
              />
              <el-table-column
                  :label="$t('common.createTime')"
                  align="center"
                  prop="createTime"
              />
              <el-table-column
                  :label="$t('common.updateTime')"
                  align="center"
                  prop="updateTime"
              />
              <el-table-column
                  label="操作"
                  align="center"
                  width="350"
                  fixed="right"
              >
                <template #default="scope">

                  <el-button
                      type="primary"
                      link
                      icon="Edit"
                      @click="updatechannel(scope.row)"
                  >{{ $t("common.edit") }}
                  </el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="handleDelete(scope.row)"
                  >{{ $t("common.delete") }}
                  </el-button
                  >
                  <!--                  <el-tooltip :content="scope.row.channelEnable != 1?$t('common.channelDisable'):$t('common.channelEnable')"  placement="top">-->
                  <!--                    <el-button-->
                  <!--                        :disabled="scope.row.channelEnable != 1"-->
                  <!--                        type="default"-->
                  <!--                        link-->
                  <!--                        icon="View"-->
                  <!--                        @click="handleDetail(scope.row.id)"-->
                  <!--                    >{{ $t("common.detail") }}</el-button-->
                  <!--                    >-->
                  <!--                  </el-tooltip>-->

                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="channelQueryForm.pageNum"
                  v-model:page-size="channelQueryForm.pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  :total="total"
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import {
  getchannelPageApi,
  getchannelListApi,
  addchannelApi,
  updatechannelApi,
  delchannelApi
} from "@/api/ems/channel/channel"
import {useRoute, useRouter} from "vue-router";
import {getEnumListByType} from "@/api/enums";
import {EmsCommonEnums} from "@/enum/common/EmsCommonEnums"
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import {useI18n} from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import {reactive, ref, onMounted, onUnmounted} from "vue";

const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const router = useRouter();
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示

const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const {t} = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 设备查询表单数据
const channelQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  channelId: null, // 设备Id
});
// 2. 设备新增表单数据
const channelForm = reactive({
  isInner : null,
  channelCnName: "", // 配置名称中文
  channelEnName: "", // 配置名称英文
  timePeriod: 1, //时间周期
  protType: null, //协议类型
  isEnable: null, //是否可用
  comment: null, //备注

});
// 3. 标签表单校验规则
const channelRules = reactive({
  channelCnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  channelEnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  timePeriod: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
  ],
  protType: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
  isEnable: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
  isInner: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
});
//
//通讯协议类别列表
const channelList = ref([]);

//查询
const search = () => {
  getSelectPage();
};

const handleSizeChange = (val) => {
  channelQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  channelQueryForm.pageNum = val;
  getSelectPage();
};
//根据协议类型ID获取协议类型名称
const getchannelTypeNameById = (id) => {
  let res = "";
  channelTypeEnums.value?.forEach(item => {
    if (item.code == id) {
      res = locale ? item.cndesc : item.endesc;
    }
  })
  return res;

}

const getisInnerTypeNameById = (id) => {
  let res = "";
  isInnerEnums.value?.forEach(item => {
    if (item.code == id) {
      res = locale ? item.cndesc : item.endesc;
    }
  })
  return res;

}
const getSelectPage = () => {
  getchannelPageApi(channelQueryForm).then((res) => {
    total.value = res.data.total;
    tableData.value = res.data.records;
  });
};
//获设备通讯协议列表
const getchannelList = () => {
  getchannelListApi().then((res) => {
    channelList.value = res.data;
  });
};
// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
const isEnableEnums = ref([]);
const isInnerEnums = ref([]);
const channelTypeEnums = ref([]);
//获取枚举列表
const getEnumListByTypeList = async (stype) => {
  let res = await getEnumListByType({type: stype});
  if (stype == EmsCommonEnums.CommonEnable) {
    isEnableEnums.value = res.data;
  }
  if (stype == EmsCommonEnums.CommonProtTypeEnum) {
    channelTypeEnums.value = res.data;
  }
  if (stype == EmsCommonEnums.CommonInnerProtEnum) {
    isInnerEnums.value = res.data;
  }
};
//新增调出弹框
const addchannel = () => {
  dialogVisible.value = true;
  Object.assign(channelForm, {
    id: null,
    channelCnName: null, // 场站Id
    channelEnName: "", // 设备中文名称
    timePeriod: "", // 时间周期
    protType: null, //协议类型
    isInner: null,
    isEnable: null, //是否可用
    comment: "", //备注
  });
  dialogTitle.value = t("channel.channelAdd");
};
//修改调出弹框
const channelId = ref();
const updatechannel = (row) => {
  dialogTitle.value = t("channel.channelUpdate");
  dialogVisible.value = true;
  channelId.value = row.id;
  Object.assign(channelForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("channel.mqttchannelAdd")) {
    addchannelApi(channelForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  } else {
    updatechannelApi(Object.assign(channelForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  }
};
//删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delchannelApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};
//跳转内部主题
const goTopic = (row)=>{
  router.push({
    path: "/comMangement/mqttInnerTopic",
    query: {
      channelConfId: row.id,
    },
  });
}
onMounted(() => {
  getSelectPage();
  getchannelList();
  getEnumListByTypeList(EmsCommonEnums.CommonEnable);
  getEnumListByTypeList(EmsCommonEnums.CommonProtTypeEnum);
  getEnumListByTypeList(EmsCommonEnums.CommonInnerProtEnum);
});
onUnmounted(() => {
});
</script>
<style lang="scss" scoped>
:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}

.app-container {
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
